package com.atguigu.service.impl;

import com.atguigu.service.CouponService;
import com.atguigu.utils.taskDisposeUtils.TaskDisposeUtils;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;

@Service
public class CouponServiceImpl implements CouponService {

    @Resource
    ThreadPoolTaskExecutor threadPool;

    //下发优惠卷数量
    public static final Integer COUPON_NUMBER = 5 * 1000000;

    @Override
    @SneakyThrows
    public void batchTaskActionV1() {

        //1 模拟要下发的优惠卷，上游系统给我们的下发优惠卷源头
        List<String> coupons = new ArrayList<>(COUPON_NUMBER);
        for (int i = 1; i <= COUPON_NUMBER; i++) {
            coupons.add("优惠卷--" + i);
        }

        //倒计时器
        CountDownLatch countDownLatch = new CountDownLatch(COUPON_NUMBER);

        //开始时间
        long startTime = System.currentTimeMillis();

        //模拟下发优惠券业务
        for (String coupon : coupons) {
            //使用线程池进行多线程操作优化
            threadPool.execute(() -> {
                try {
                    System.out.println("多线程一次下发500w张优惠券功能，当前为：" + coupon);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        //倒计时等待
        countDownLatch.await();

        //结束时间
        long endTime = System.currentTimeMillis();

        System.out.println("----任务处理完毕costTime: " + (endTime - startTime) + " 毫秒");
    }

    @Override
    @SneakyThrows
    public void batchTaskActionV2() {
        //1 模拟要下发的优惠卷，上游系统给我们的下发优惠卷源头
        List<String> coupons = new ArrayList<>(COUPON_NUMBER);
        for (int i = 1; i <= COUPON_NUMBER; i++) {
            coupons.add("优惠卷--" + i);
        }

        //开始时间
        long startTime = System.currentTimeMillis();

        //模拟下发优惠券业务
        TaskDisposeUtils.send(coupons, threadPool, TaskDisposeUtils::disposeTask);

        //结束时间
        long endTime = System.currentTimeMillis();

        System.out.println("----任务处理完毕costTime: " + (endTime - startTime) + " 毫秒");
    }
}
